package com.qst.yunpan.controller.customer;

import com.qst.yunpan.entity.User;
import com.qst.yunpan.service.FileService;
import com.qst.yunpan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    //切记：在所有的界面层，一定会有业务逻辑层的对象
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;
    //初始直接跳转到登录界面
    @RequestMapping("/todologin")
    public String todologin(){
        return "login";
    }
    @RequestMapping("/toregister")
    public String toregister(){
        return "register";
    }

    //实现登录判断，并进行相应的跳转
    @RequestMapping("/login.action")
    public String login(String username, String password, HttpSession session,HttpServletRequest request){
        if(userService.login(username, password) != null){
            //登录成功
            User user = userService.login(username, password);
            session.setAttribute("user",user);
            return "redirect:/customer/index.action";
        }else{
            //登录失败
            request.setAttribute("msg","用户名或密码不正确！");
            return "login";
        }
    }

    //实现注册
    @RequestMapping("/register.action")
    public String register(User user, HttpServletRequest request){
        System.out.println(user.toString()+"&&&&&&&&&&&");
        user.setCountsize("0.0B");
        user.setTotalsize("10.0GB");
        if(user.getUsername() == null || user.getUsername().equals("") || user.getPassword() ==null || user.getPassword().equals("")){
            request.setAttribute("msg","请输入用户名和密码");
            return "register";
        }else{
            boolean isSuccess = userService.register(user);
            if(isSuccess){
                fileService.addNewNameSpace(request,user.getUsername());
                return "login";
            }else{
                request.setAttribute("msg","存在相同的账户，注册失败");
                return "register";
            }
        }
    }

    //退出功能
    @RequestMapping("/logout.action")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        session.invalidate(); //设置session 失效
        return "login";
    }

}
